import 'dart:io';
import 'package:common_utils/common_utils.dart';
import 'package:fate_blind_box/config/app_utils.dart';
import 'package:fate_blind_box/config/event_bus.dart';
import 'package:fate_blind_box/config/event_keys.dart';
import 'package:fate_blind_box/routes/app_pages.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'config/device_token_manger.dart';
import 'network/http_config.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (Provider.memberId.isEmpty) {
    Provider.memberId = await Provider.getCache("memberId");
  }
  if (HttpConfig.token.isEmpty) {
    HttpConfig.token = await Provider.getCache("token");
    Provider.profilePhoto = await Provider.getCache("profilePhoto");
  }
  _initWechat();
  if (!kIsWeb) {
    //初始化环信
    await _initSDK();
  }
  if (Platform.isAndroid) {
    SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.light);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
  // getDeviceToken();
  runApp(const MyApp());
}

/// 获取token
getDeviceToken() async {
  const channelId = 'com.example.app/get/token'; // 定义与原生端相同的通道名称
  const MethodChannel methodChannel = MethodChannel(channelId);
  methodChannel.setMethodCallHandler(_handleMethodCall);
}

// 处理从原生端发送的令牌数
Future<dynamic> _handleMethodCall(MethodCall call) async {
  switch (call.method) {
    case 'onTokenReceived':
      final String token = call.arguments as String;
      DeviceTokenManger.instance.setHuaWei(token);
      LogUtil.e('上传token:${DeviceTokenManger.huawei}-------${token}');
      EMClient.getInstance.pushManager.updateHMSPushToken(token);
      return;
    default:
      throw PlatformException(
          code: 'NotImplemented',
          details: "Method '${call.method}' not implemented");
  }
}

/// 初始化微信SDK
Future? _initWechat() async {
  return fluwx.registerWxApi(
      appId: Provider.wechatAppID,
      doOnAndroid: true,
      doOnIOS: true,
      universalLink: HttpConfig.baseUrl
      // universalLink: "${HttpConfig.baseUrl}ios"
      );
}

/// 初始化环信sdk
Future? _initSDK() async {
  EMOptions options = EMOptions(
    appKey: "1168230328160038#ouranyj",
    // appKey: "1168230328160038#demo",
    autoLogin: true,
  );
  options.enableAPNs('ouranyujian_release');
  print('环信注册成功');

  options.enableOppoPush(
      'd367e5ea67334b2eb9e8ac563a0cddce', '0102b4eec21c446cbcfa54bf666aff86');
  options.enableVivoPush();
  // options.enableMiPush('2882303761520263769', '5222026312769');
  options.enableHWPush();

  await EMClient.getInstance.init(options);
  // 通知 SDK UI 已准备好。该方法执行后才会收到 `EMChatRoomEventHandler`、`EMContactEventHandler` 和 `EMGroupEventHandler` 回调。
  await EMClient.getInstance.startCallback();
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return RefreshConfiguration(
      headerBuilder: () => const WaterDropHeader(),
      // 配置默认头部指示器,假如你每个页面的头部指示器都一样的话,你需要设置这个
      footerBuilder: () => const ClassicFooter(),
      // 配置默认底部指示器
      headerTriggerDistance: 80,
      // 头部触发刷新的越界距离
      springDescription:
          const SpringDescription(stiffness: 170, damping: 16, mass: 1.9),
      // 自定义回弹动画,三个属性值意义请查询flutter api
      maxOverScrollExtent: 100,
      //头部最大可以拖动的范围,如果发生冲出视图范围区域,请设置这个属性
      maxUnderScrollExtent: 0,
      // 底部最大可以拖动的范围
      enableScrollWhenRefreshCompleted: true,
      //这个属性不兼容PageView和TabBarView,如果你特别需要TabBarView左右滑动,你需要把它设置为true
      enableLoadingWhenFailed: true,
      //在加载失败的状态下,用户仍然可以通过手势上拉来触发加载更多
      hideFooterWhenNotFull: false,
      // Viewport不满一屏时,禁用上拉加载更多功能
      enableBallisticLoad: true,
      // 可以通过惯性滑动触发加载更多
      child: ScreenUtilInit(
        designSize: const Size(390, 844),
        minTextAdapt: true,
        builder: (context, child) {
          return GetMaterialApp(
            localizationsDelegates: const [
              RefreshLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate
            ],
            supportedLocales: const [
              Locale('zh', 'CH'),
              Locale('en', 'US'),
            ],
            locale: const Locale('zh'),
            getPages: AppPages.routes,
            debugShowCheckedModeBanner: false,
            title: '都肆商圈',
            initialRoute: PageRouteNames.main,
            defaultTransition: Transition.cupertino,
            // routes: IMKitRouter.instance.routes,
            theme: ThemeData(
              highlightColor: Colors.transparent,
              splashFactory: NoSplash.splashFactory,
              primaryColor: const Color(0xffFFFFFF),
              pageTransitionsTheme: const PageTransitionsTheme(builders: {
                TargetPlatform.android: CupertinoPageTransitionsBuilder(),
                TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
              }),
              appBarTheme: const AppBarTheme(
                  backgroundColor: Colors.white,
                  elevation: 0,
                  iconTheme: IconThemeData(
                    color: Color(0xff333333),
                  ),
                  titleTextStyle: TextStyle(
                    fontSize: 16,
                    color: Color(0xff333333),
                  ),
                  systemOverlayStyle: SystemUiOverlayStyle.dark),
            ),
            builder: (context, widget) {
              return MediaQuery(
                //设置文字大小不随系统设置改变
                data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
                child: FlutterEasyLoading(
                    child: InkWell(
                        onTap: () => _hideKeyboard(context), child: widget)),
              );
            },
          );
        },
      ),
    );
  }

  void _hideKeyboard(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
    if (AppUtils.isShowKeyboard) {
      EventBus.instance.commit(eventName: EventKeys.offKeyBoard);
    }
  }
}
